import { Resolver, Query, Args, Int, Mutation } from '@nestjs/graphql';
import { Cat } from './entities/cat.entity';

@Resolver(() => Cat)
export class AppResolver {
  private cats: Cat[] = [
    new Cat(1, 'Tom', 3, '英国短毛猫'),
    new Cat(2, '', 2, '暹罗'),
    new Cat(3, 'Mimi', 1, '布偶猫'),
    new Cat(4, 'Kitty', 4, '短毛猫'),
    new Cat(5, 'Pinky', 5, '短毛猫'),
    new Cat(6, 'Lucy', 6, '短毛猫'),
  ];

  @Query(() => [Cat])
  getCats(): Cat[] {
    return this.cats;
  }

  @Query(() => Cat)
  getCatById(@Args('id', { type: () => Int }) id: number): Cat {
    const cat = this.cats.find((cat) => cat.getId() === id);
    if (!cat) {
      throw new Error(`Cat with id ${id} not found`);
    }
    return cat;
  }

  @Query(() => String)
  hello() {
    return 'hello world';
  }

  @Mutation(() => Cat)
  deleteById(@Args('id', { type: () => Int }) id: number): Cat {
    const index = this.cats.findIndex((cat) => cat.getId() === id);
    if (index === -1) {
      throw new Error(`Cat with id ${id} not found`);
    }
    const deletedCat = this.cats.splice(index, 1)[0];
    return deletedCat;
  }
}
